﻿using System;
using Microsoft.Practices.SLUnity;
using StopLight.Interfaces;
using Stoplight.Events;
using Stoplight.Base;
using Stoplight.Interfaces;

namespace StopLight.Services {

    public class StoplightScheduleService : ServiceBase, IStoplightScheduleService 
    {
        private IStoplightTimerService timer;
        private TimeSpan[] lightTimes = new TimeSpan[3];
        private int currentLight = 0;

        public StoplightScheduleService(IStoplightTimerService timer)
        {
            this.timer = timer;
            timer.Expired += OnTimerExpired;
        }

        public void Start() 
        {
            timer.Start();
        }

        public void Update(TimeSpan green, TimeSpan yellow, TimeSpan red) 
        {
            lightTimes[0] = green;
            lightTimes[1] = yellow;
            lightTimes[2] = red;

            Logger.Log(string.Format("UPDATE SCHEDULE: {0} {1} {2}", green, yellow, red),
                Category.Debug, Priority.None);
        }

        public void ForceChange() 
        {
            OnTimerExpired(this, EventArgs.Empty);
            Logger.Log(string.Format("FORCED CHANGE"), Category.Debug, Priority.None);
        }

        private void OnTimerExpired(object sender, EventArgs e) 
        {
            EventAggregator.GetEvent<ChangeLightEvent>().Publish(new ChangeLightEvent());

            currentLight = (currentLight + 1) % 3;
            timer.Duration = lightTimes[currentLight];
            timer.Start();
        }
    }
}
